// 参数处理类
import {InterfaceUser} from '@/interface/InterfaceUser';
import {InterfaceResponse} from '@/interface/InterfaceResponse';


export default class CommonUnit {

    public static argumentWithUser(user: object = {}, arg: object = {}): object {

        if (JSON.stringify(user) === '{}') {
            return arg;
        } else if ((user as InterfaceUser).token) {
            return {};
        } else {
            return arg;
        }
    }

    public static responseLoginVerification(res: InterfaceResponse): boolean {
        if (res.code === -1) {
            return false;
        }
        return true;
    }

    public static decodeHtml(s: string): string {
        return s
            .replace(s ? /&(?!#?\w+;)/g : /&/g, '&amp;')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"')
            .replace(/&#39;/g, '\'');
    }

    // 解决微信6.7.4 搭配IOS12+ H5页面里的select,input软键盘弹起的时候页面会上移，
    // 软键盘关闭页面不会下移，导致页面空缺了一部分。
    public static windowSizeRecover(n: number = 0): boolean {
        setTimeout(() => {
            if (n !== -1) {
                window.scrollTo(0, 0);
            } else {
                window.scrollTo(0, document.documentElement.clientHeight);
            }
        }, 100);
        return true;
    }

    // 随机数生成器
    public static randomNumBoth(min: number, max: number): number {
        const range: number = max - min;
        const rand: number = Math.random();
        // 四舍五入
        return (min + Math.round(rand * range));
    }

    // 判断是否在圆内
    public static pointInsideCircle(point: number[], circle: number[], r: number = 0) {
        if (r === 0) {
            return false;
        }
        const dx: number = circle[0] - point[0];
        const dy: number = circle[1] - point[1];
        return dx * dx + dy * dy <= r * r;
    }

    // 下划线转驼峰法
    public static objectUnderlineToHump(obj: any): any {
        const newObj = {};
        Object.keys(obj).forEach((key: string) => {
            // key,obj[key]
            const humpKey: string = key.toLowerCase().replace(/_([a-z])/g, (all, letter) => {
                return letter.toUpperCase();
            });
            if (obj[key] !== null && !Array.isArray(obj[key]) && typeof (obj[key]) === 'object') {
                (newObj as any)[humpKey] = CommonUnit.objectUnderlineToHump(obj[key]);
            } else {
                (newObj as any)[humpKey] = obj[key];
            }

        });

        return newObj;
    }

    // 首字母大写，下划线转驼峰法
    public static arrayUnderlineToHump(arr: any): any {
        const newArr: string[] = [];
        arr.forEach((value: string, key: number) => {
            value = value.toLowerCase().replace(/_([a-z])/g, (all, letter) => {
                return letter.toUpperCase();
            });
            value = value.substring(0, 1).toUpperCase() + value.substring(1);
            newArr.push(value);
        });
        return newArr;
    }

    // 随机数
    public static getRandomNum(Min: number, Max: number): number {
        const range: number = Max - Min;
        const rand: number = Math.random();
        return (Min + Math.round(rand * range));
    }

    // 把返回的结果数组干成picker的格式
    public static resultToPickerData(list: any[]) {
        const newList: any[] = [];
        for (const item of list) {
            newList.push({text: item.name, value: item.alias, data: item});
        }
        return newList;
    }

    // 判断设备类型
    public static deviceType() {
        const ua: string = navigator.userAgent;
        const isAndroid: boolean = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1; // android终端
        const isiOS: boolean = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
        return {isAndroid, isiOS};
    }

    // 判断是否为微信浏览器
    public static wechatBrowser(): boolean {
        const ua: string = navigator.userAgent.toLowerCase();
        return String(ua.match(/MicroMessenger/i)) === 'micromessenger';
    }

    public static getQueryString(name: string, url: string): string {
        const urlSplit: string[] = url.split('?');
        if (urlSplit.length > 1) {
            const query: string = urlSplit[1] || '';
            const queryList: any = query.split('&');
            // tslint:disable-next-line:prefer-for-of
            for (let i = 0; i < queryList.length; i++) {
                const pair = queryList[i].split('=');
                if (String(pair[0]) === String(name)) {
                    return pair[1];
                }
            }
            return '';
        } else {
            return '';
        }
        // var vars = query.split("&");
        // for (var i=0;i<vars.length;i++) {
        //     var pair = vars[i].split("=");
        //     if(pair[0] == variable){return pair[1];}
        // }
        // return(false);
    }

    public static phoneReplaceStar(phone: string) {
        const reg = /^(\d{3})\d*(\d{4})$/;
        return phone.replace(reg, '$1****$2');
    }

    public static getRandomString(len: number = 32): string {
        len = len || 32;
        const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        const maxPos = $chars.length;
        let pwd = '';
        for (let i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    public static converSize(size: number): string {
        let sizeStr = '';
        if (size < 0.1 * 1024) {
            // 如果小于0.1KB转化成B
            sizeStr = size.toFixed(2) + 'B';
        } else if (size < 0.1 * 1024 * 1024) {
            // 如果小于0.1MB转化成KB
            sizeStr = (size / 1024).toFixed(2) + 'KB';
        } else if (size < 0.1 * 1024 * 1024 * 1024) {
            // 如果小于0.1GB转化成MB
            sizeStr = (size / (1024 * 1024)).toFixed(2) + 'MB';
        } else if (size < 0.1 * 1024 * 1024 * 1024 * 1024) {
            // GB
            sizeStr = (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
        } else {
            // TB
            sizeStr = (size / (1024 * 1024 * 1024 * 1024)).toFixed(2) + 'TB';
        }
        return sizeStr;
    }
}
